package com.mgvlife.ddlw.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.springframework.stereotype.Service;

import com.mgvlife.ddlw.entity.Clazz;
import com.mgvlife.ddlw.entity.Schedule;
import com.mgvlife.ddlw.entity.SignInInfo;
import com.mgvlife.ddlw.entity.Student;
import com.mgvlife.ddlw.formbean.StudentForm;
import com.mgvlife.ddlw.service.StudentService;
import com.mgvlife.ddlw.vo.Result;
import com.mgvlife.ddlw.vo.VoStudent;
import com.xinhuo.dao.DaoSupport;
import com.xinhuo.util.DateUtil;
import com.xinhuo.util.QueryResult;
import com.xinhuo.vo.JsonEasyUI;

@Service("studentService")
public class StudentServiceImpl extends DaoSupport implements StudentService {

	public Result studentAdd(StudentForm dataForm) throws Exception {
		String stuId = dataForm.getStuId();
		boolean isStudentExist = this.checkStudentExist(stuId);
		if (isStudentExist) {
			return new Result("error", "学生已存在");
		}
		Student student = new Student();
		student.setId(UUID.randomUUID().toString());
		student.setOpenId(null);
		student.setName(dataForm.getName());
		student.setStuId(dataForm.getStuId());
		student.setImgUrl("");
		Clazz clazz = this.findById(Clazz.class, dataForm.getClazzId());
		if (clazz == null) {
			return new Result("error", "无此班级存在");
		}
		student.setClazz(clazz);
		student.setSignInInfos(new ArrayList<SignInInfo>());
		clazz.getStudents().add(student);
		this.save(student);
		// this.update(clazz);
		return Result.success();
	}

	public Result studentUpdate(StudentForm dataForm) throws Exception {
		String id = dataForm.getId(), stuId = dataForm.getStuId();
		boolean isStudentExist = this.checkStudentExist(stuId);
		Student student = this.findById(Student.class, id);
		if (student == null)
			return new Result("error", "无此学生");
		if (!student.getStuId().equals(stuId) && isStudentExist) {
			return new Result("error", "学生已存在");
		}
		if (dataForm.getClazzId() != null && !dataForm.getClazzId().equals("")
				&& student.getClazz().getId() != dataForm.getClazzId()) {
			Clazz clazz = student.getClazz();
			clazz.getStudents().remove(student);
			clazz = this.findById(Clazz.class, dataForm.getClazzId());
			clazz.getStudents().add(student);
			student.setClazz(clazz);
			// this.update(clazz);
		}
		student.setName(dataForm.getName());
		student.setStuId(stuId);
		// student.setOpenId(dataForm.getOpenId());
		this.update(student);
		return Result.success();
	}

	public JsonEasyUI<VoStudent> getData(StudentForm dataForm) {
		JsonEasyUI<VoStudent> result = new JsonEasyUI<VoStudent>();
		QueryResult<Student> qr = this.getScrollData(Student.class, null, null,
				dataForm.getSearchTitle(), dataForm.getSearch(),
				dataForm.getPage(), dataForm.getRows(), dataForm.getSort(),
				dataForm.getOrder());
		result.setTotal(qr.getTotalrecord());
		List<VoStudent> student_l = new ArrayList<VoStudent>();
		for (Student student : qr.getResultList()) {
			student_l.add(new VoStudent(student));
		}
		result.setRows(student_l);
		return result;
	}

	public Result studentDelete(StudentForm dataForm) throws Exception {
		String stuId = dataForm.getId();
		if (stuId != null && stuId.length() > 0) {
			String whereSQL = "";
			String[] ids = stuId.split(";");
			boolean isFirst = true;
			for (int i = 0; i < ids.length; i++) {
				if (isFirst) {
					whereSQL = "id in (?";
					isFirst = false;
				} else {
					whereSQL += ", ?";
				}
			}
			whereSQL += ")";
			List<Student> students = this.findAll(Student.class, whereSQL, ids);
			for (Student student : students) {
				Clazz clazz = student.getClazz();
				clazz.getStudents().remove(student);
				for (SignInInfo signInInfo : student.getSignInInfos()) {
					signInInfo.getSchedule().getSignInInfos()
							.remove(signInInfo);
					signInInfo.setStudent(null);
				}
				this.delete(student);
			}
		} else {
			return new Result("error", "学生不存在");
		}
		return Result.success();
	}

	public Result signIn(StudentForm dataForm) throws Exception {
		String openId = dataForm.getOpenId();
		String whereSQL0 = "openId=?";
		Object[] whereParams0 = { openId };
		Student student = this.find(Student.class, whereSQL0, whereParams0);
		if (student == null) {
			return new Result("unBind", "尚未绑定");
		}
		Schedule schedule = this.findById(Schedule.class,
				dataForm.getScheduleId());
		if (schedule == null) {
			return new Result("error", "无此课次");
		}
		String whereSQL1 = "student=? and schedule=?";
		Object[] whereParams1 = { student, schedule };
		SignInInfo signInInfo = this.find(SignInInfo.class, whereSQL1,
				whereParams1);
		if (signInInfo != null) {
			if (signInInfo.getSignInStatus() == 1) {
				return new Result("success", "你已签到");
			}
			signInInfo.setSignInStatus(1);
			signInInfo.setSignInTime(DateUtil.dataToString(new Date()));
			this.update(signInInfo);
		} else {
			return new Result("error", "不存在此点到信息");
		}
		return new Result("success", "签到成功");
	}

	public Result bindOpenId(StudentForm dataForm) throws Exception {
		String openId = dataForm.getOpenId();
		String stuId = dataForm.getStuId();
		String whereSQL0 = "openId=?";
		Object[] whereParams0 = { openId };
		Student student = this.find(Student.class, whereSQL0, whereParams0);
		if (student != null) {
			if (!student.getStuId().equals(stuId))
				return new Result("error", "此微信号已绑定");
			else
				return new Result("success", "你已绑定");
		} else {
			String whereSQL1 = "stuId=? and name=?";
			Object[] whereParams1 = { stuId, dataForm.getName() };
			System.out.println("!!" + stuId + dataForm.getName());
			Student student1 = this.find(Student.class, whereSQL1, whereParams1);
			if (student1 == null)
				return new Result("error", "无此学生");
			if (student1.getOpenId() != null)
				return new Result("error", "此学号已绑定");
			student1.setOpenId(openId);
			this.update(student1);
		}
		return new Result("success", "绑定成功");
	}

	public boolean checkStudentExist(String stuId) {
		String whereSQL = "stuId=?";
		Object[] whereParams = { stuId };
		long count = this.getDataCount(Student.class, whereSQL, whereParams);
		return count > 0;
	}

}
